#include "countingtab.h"
#include "ui_countingtab.h"

CountingTab::CountingTab(QWidget *parent) :
    QWidget(parent), m_ui(new Ui::CountingTab),
    imgL(0), sCounter(new SeedCounter),counted(false)

{
    m_ui->setupUi(this);
    connect(m_ui->countButton, SIGNAL(clicked()), this, SLOT(count()));
    connect(m_ui->totalButton, SIGNAL(clicked()), this, SLOT(total()));
}

CountingTab::~CountingTab()
{
    delete m_ui;
    if(sCounter) delete sCounter;
}

void CountingTab::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        m_ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void CountingTab::addLoader(ImageLoader *loader)
{
    if(loader)
    {
        m_ui->gridLayout->addWidget(loader, 0, 0);
        imgL = loader;
    }
}

void CountingTab::showContent()
{
    if(imgL  != 0)
        m_ui->gridLayout->addWidget(imgL, 0, 0);
}

void CountingTab::count()
{
    int total = 0;
    if(imgL)
    {
        imgL->clearDisplay();

        QString currFile = imgL->getCurrFile();
        if(currFile.length() > 0)
        {
            if(sCounter->addFile(currFile))
            {
                counted = true;
                total = sCounter->numberOfSeeds();
                m_ui->sTotalLabel->setText(QString::number(total));

                imgL->addResultImg(sCounter->getResultImg());

                // Assume each dish contains exactly 50 seeds
                if(total > 50)
                    m_ui->missLabel->setText(QString::number(total - 50));
                else
                    m_ui->missLabel->setText(QString::number(50 - total));
            }
            else
            {
                QMessageBox msgBox;
                msgBox.setText("This type of experiment is not supported!  ");
                msgBox.exec();
            }
        }
    }    
}

void CountingTab::total()
{
    int total = 0;
    int seeds = 0;

    QMessageBox msgBox;
    QVector<QString> files = imgL->getFiles();

    if(files.size() > 0)
    {
        msgBox.setText("Please note this require several minutues.");
        msgBox.exec();

        QString file;
        for(int i = 0; i < files.size(); i++)
        {
            file = files.at(i);
            sCounter->addFile(file);
            seeds = sCounter->numberOfSeeds();
            total += seeds;
        }
        if(total > 0)            
            m_ui->sTotalLabel_2->setText(QString::number(total));
    }
    else
    {
        qDebug() << "Error";
    }
}

void CountingTab::hasCount()
{
    if(!counted)
        count();
    emit seedCounted(sCounter);
}

